import { showModal, showToast, requestPayment } from '../../utils/showmodel.js'
import { request } from "../../request/index"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  //当页面渲染完毕触发
  onShow() {
    //获取缓存的地址
    const address = wx.getStorageSync('address');
    //拿到缓存在strong中的商品数组cart
    let cart = wx.getStorageSync('cart') || [];
    //过滤出被勾选的商品
    cart = cart.filter(item => item.checked)
    this.setTotalInfo(cart)
    this.setData({
      address
    })
  },




  //设置购物车状态的同时 重新计算 底部工具栏的各个价格属性
  setTotalInfo(cart) {
    //获取总价格 和总数量
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(item => {
      if (item.checked) {
        totalPrice += item.num * item.goods_price
        totalNum += item.num
      }
    })

    //将cart数组重新放进data和缓存中
    this.setData({
      cart,
      totalPrice,
      totalNum,
    })
    wx.setStorageSync("cart", cart);
  },
  //微信支付  只有企业账号才能使用 企业账号的小程序后台中，必须给用户添加白名单
  //点击支付
  async handlePays() {
    try {
      //判断是否有缓存的token令牌
      const token = wx.getStorageSync('token');
      if (!token) {
        //跳转到授权界面
        wx.navigateTo({
          url: '/pages/order/index',
        });
      } else {
        //已经存在token 创建订单  准备预支付 发起微信支付 查询订单
        //3.1:准备请求头参数
        // const header = { Authorization: token }
        //3.2准备请求体参数
        const order_price = this.data.totalPrice
        const consignee_addr = this.data.address.provinceName + this.data.address.cityName
          + this.data.address.countyName + this.data.address.detailInfo
        let goods = []
        let { cart } = this.data
        cart.forEach(v => goods.push({
          goods_id: v.goods_id,
          goods_number: v.goods_number,
          goods_price: v.goods_price
        }))
        //整合参数
        const orderParams = { order_price, consignee_addr, goods }
        //发起创建订单的请求
        const { data: res } = await request({
          url: '/my/orders/create',
          method: 'POST',
          data: orderParams,
        })
        //获取订单号编号
        const order_number = res.message.order_number
        //获取支付参数
        const { data: res1 } = await request({
          url: '/my/orders/req_unifiedorder',
          method: 'POST',
          data: { order_number }, 
        })
        const pay = res1.message.pay
        //设置支付二维码 发起微信支付
        // const result = await requestPayment(pay)
        //查询订单状态是否成功
        const { data: res2 } = await request({
          url: '/my/orders/chkOrder',
          method: 'POST',
          data: { order_number },
        })
        await showToast({ title: '支付成功', icon: 'success' })
        //手动删除缓冲中已经支付了的商品数据
        let newCart = wx.getStorageSync('cart');
        //过滤掉已被勾选的项
        newCart = newCart.filter(v => !v.checked)
        //将过滤后的数组缓存回去
        wx.setStorageSync('cart',newCart);
        //支付成功后 跳转到订单界面
        wx.navigateTo({
          url: '/pages/auth/index',
        });
      }
    } catch (error) {
      await showToast({ title: '支付失败', icon: 'error' })
      console.log(error)
    }
  }

})